# -*- coding:utf-8 -*-
# @FileName : app/services/history_service.py
# @Time     : 2025/11/28
# @Author   : 天空之城

"""
History 统一服务层

- 提供给业务代码使用：创建任务历史、更新状态等
- 提供给 API 路由使用：列表、单条详情、删除、导出等
"""

from datetime import datetime
from typing import List, Dict, Any, Optional

from flask import g

from app.models import History
from app.extensions import db, logger


class HistoryService:
    """History 统一服务类"""

    # ========== 通用业务接口（可在任意业务模块调用） ==========

    @staticmethod
    def create_history(
        user_id: int,
        title: str,
        description: str = "",
        status: str = "pending",
        type: str = "normal",
        can_replay: bool = False,
    ) -> Optional[History]:
        """
        创建历史记录（通用业务方法）

        Args:
            user_id: 用户ID
            title: 任务标题
            description: 描述
            status: 任务状态（completed/pending/failed/replay 等）
            type: 任务类型（normal/replay 等）
            can_replay: 是否可以回放

        Returns:
            History 或 None
        """
        try:
            h = History(
                user_id=user_id,
                title=title,
                description=description,
                status=status,
                type=type,
                canReplay=can_replay,
                timestamp=datetime.now(),
            )
            db.session.add(h)
            db.session.commit()
            return h
        except Exception as e:
            db.session.rollback()
            logger.error(f"[HistoryService] 创建历史记录失败: {e}")
            return None

    @staticmethod
    def update_history(history_id: int, **kwargs) -> Optional[History]:
        """
        更新历史记录（通用业务方法）

        Args:
            history_id: 历史记录ID
            **kwargs: 要更新的字段和值

        Returns:
            更新后的 History 或 None
        """
        try:
            h: History = History.query.filter_by(id=history_id).first()
            if not h:
                return None

            for key, val in kwargs.items():
                if hasattr(h, key):
                    setattr(h, key, val)

            db.session.commit()
            return h
        except Exception as e:
            db.session.rollback()
            logger.error(f"[HistoryService] 更新历史记录失败: {e}")
            return None

    # ========== 提供给 API 使用的接口（封装用户维度） ==========

    @staticmethod
    def list_histories_for_user(
        user_id: int,
        limit: int = 20,
        offset: int = 0,
    ) -> List[Dict[str, Any]]:
        """
        获取当前用户的历史记录列表（按时间倒序）

        Returns:
            历史记录字典列表
        """
        try:
            histories = (
                History.query.filter_by(user_id=user_id)
                .order_by(History.timestamp.desc())
                .limit(limit)
                .offset(offset)
                .all()
            )
            return [h.to_dict() for h in histories]
        except Exception as e:
            logger.error(f"[HistoryService] 获取历史记录列表失败: {e}")
            raise

    @staticmethod
    def get_history_for_user(
        user_id: int,
        record_id: int,
    ) -> Optional[Dict[str, Any]]:
        """
        获取当前用户的一条历史记录
        """
        try:
            history = History.query.filter_by(id=record_id, user_id=user_id).first()
            return history.to_dict() if history else None
        except Exception as e:
            logger.error(f"[HistoryService] 获取历史记录失败: {e}")
            raise

    @staticmethod
    def delete_history_for_user(user_id: int, record_id: int) -> bool:
        """
        删除当前用户的一条历史记录
        """
        try:
            history = History.query.filter_by(id=record_id, user_id=user_id).first()
            if not history:
                return False

            db.session.delete(history)
            db.session.commit()
            return True
        except Exception as e:
            logger.error(f"[HistoryService] 删除历史记录失败: {e}")
            db.session.rollback()
            raise

    @staticmethod
    def delete_all_histories_for_user(user_id: int) -> int:
        """
        删除当前用户的所有历史记录

        Returns:
            删除条数
        """
        try:
            deleted_count = History.query.filter_by(user_id=user_id).delete()
            db.session.commit()
            return deleted_count
        except Exception as e:
            logger.error(f"[HistoryService] 删除所有历史记录失败: {e}")
            db.session.rollback()
            raise

    @staticmethod
    def export_histories_for_user(
        user_id: int,
        format: str,
        include: Optional[list] = None,
        filters: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """
        导出历史记录（给 API 用）

        Args:
            user_id: 用户ID
            format: 导出格式（json/csv/pdf）
            include: 包含的数据类型（summary/details/statistics/screenshots）
            filters: 筛选条件
        """
        include = include or []
        filters = filters or {}

        try:
            if format not in ["json", "csv", "pdf"]:
                raise ValueError(f"不支持的导出格式: {format}")

            # 构造基础查询
            query = History.query.filter_by(user_id=user_id)

            # 应用筛选
            if "status" in filters:
                query = query.filter(History.status.in_(filters["status"]))
            if "type" in filters:
                query = query.filter(History.type.in_(filters["type"]))
            if "dateRange" in filters:
                from datetime import datetime as dt
                date_range = filters["dateRange"]
                if "start" in date_range:
                    start_date = dt.strptime(date_range["start"], "%Y-%m-%d %H:%M:%S")
                    query = query.filter(History.timestamp >= start_date)
                if "end" in date_range:
                    end_date = dt.strptime(date_range["end"], "%Y-%m-%d %H:%M:%S")
                    query = query.filter(History.timestamp <= end_date)

            histories = [h.to_dict() for h in query.all()]

            now_str = datetime.now().strftime("%Y%m%d_%H%M%S")

            if format == "json":
                import json

                content = json.dumps(histories, ensure_ascii=False, indent=2)
                return {
                    "format": "json",
                    "content": content,
                    "filename": f"history_export_{now_str}.json",
                }

            if format == "csv":
                import csv
                from io import StringIO

                if not histories:
                    return {
                        "format": "csv",
                        "content": "",
                        "filename": f"history_export_{now_str}.csv",
                    }

                output = StringIO()
                fieldnames = histories[0].keys()
                writer = csv.DictWriter(output, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerows(histories)

                return {
                    "format": "csv",
                    "content": output.getvalue(),
                    "filename": f"history_export_{now_str}.csv",
                }

            if format == "pdf":
                # 简化实现：真正 PDF 可以后续接第三方库
                logger.warning("PDF导出功能尚未完全实现")
                return {
                    "format": "pdf",
                    "content": f"PDF导出功能尚未完全实现，共包含{len(histories)}条记录",
                    "filename": f"history_export_{now_str}.pdf",
                }

            # 理论上到不了这里
            raise ValueError(f"不支持的导出格式: {format}")

        except ValueError as e:
            logger.error(f"[HistoryService] 导出历史记录参数错误: {e}")
            raise
        except Exception as e:
            logger.error(f"[HistoryService] 导出历史记录失败: {e}")
            raise